package com.wawayaya.bookreader.ViewPages;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import com.wawayaya.bookreader.bean.Pagedata;
import com.wawayaya.bookreader.DefaultSettings;
import com.wawayaya.bookreader.bean.StringIntQuadruple;
import com.wawayaya.util.Devicescreenbasicinfo;
import com.wawayaya.util.ImageUtils;
import com.wawayaya.util.TLog;
import com.wbtech.ums.UmsAgent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import wawayaya.kids_iread.R;
import com.wawayaya.bookreader.Imutualaction;
import com.wawayaya.bookreader.bean.AudiofileTimeelapsedUnit;
import com.wawayaya.bookreader.bean.DictData;
import com.wawayaya.bookreader.bean.DictRegion;
import com.wawayaya.bookreader.bean.EnDictData;
import com.wawayaya.bookreader.bean.HotRegionData;
import com.wawayaya.bookreader.bean.IntDouble;
import com.wawayaya.bookreader.bean.KokRegion;

/**
 * 每个页面（ 每次初始三页：当前页、前后各一页 ）
 *  1. 显示背影图、前景图
 *  2. 走红（卡拉OK）
 *  3. 播放音频
 *  4. 启动语速调节
 *  5. touch事件(缩放功能)
 *  6. 所点击事件控制（如取词、当前页titleBar、缩放引导页的显示）
 */
public class NewBookPageView extends View {

    private static final String TAG = "kok";
    private Pagedata m_pd = null;
    private DictRegion m_dr = null;
    private Bitmap m_bmpBkg = null;
    private int m_iinnerpage = -1;
    private AtomicBoolean m_bselected = new AtomicBoolean(false);
    private float m_fratio = 1.0f;

    private int m_idecoderatio = 1;
    private Context m_ct = null;
    private int m_ishowpinyin = 0; // 0, hide; 1, show 
    private int m_ishowanotherlan = 0; // 0, hide; 2, show
    private Imutualaction m_mutualactioncallback = null;
    private int m_ikokcolor = Color.RED;
    private int m_inetid = 0;
    private int m_ibookid = 0;
    private int m_iviewXoffset = 0;
    private int m_iviewYoffset = 0;

    private long m_llasttimeworddictshow = 0;
    private Devicescreenbasicinfo m_dsi = null;
    private int m_ireadtype = DefaultSettings.BOOKREADTYPE_READMYSELF;

    private final static int ms_imsgplaykok = 0;
    private final static int ms_imsgautokok = 1;
    private final static int ms_imsgstopkok = 2;
    private static final int KOK_SLICETIME = 50; //milliseconds
    private static final int KOK_AUDIOFILEINTERVALTIME = 100; //milliseconds
    private static final int KOK_ENDLASTTIME = 100; //milliseconds
    private boolean m_bkokisplaying = false;
    private AtomicBoolean m_closekokimmediately = new AtomicBoolean(false);
    private Bitmap m_bmpchnfore = null;
    private ArrayListtoNext<kokfilesoundregion> m_alkokfiletimeregions = null;//new ArrayListtoNext<kokfilesoundregion>();
    private int m_lastkokunitposforonefile = -1;
    private ArrayList<Rect> m_alrckok = new ArrayList<Rect>();
    private Rect m_rckoklastdraw = null;
    private int m_ikokfilestartrectleft = 0;
    private myMediaPlayer m_mpkokplayer = null;
    private Paint m_ptkok = new android.graphics.Paint(Paint.DITHER_FLAG);

    private Timer m_tmkok = null;
    private TimerTask m_ttkoktask = null;

/*	private int m_imovestartX = -100;
	private int m_imovestartY = -100;
	private int m_imoveendX = -100;
	private int m_imoveendY = -100;*/

	private Rect m_alrckokOnDraw[];
	private float  m_bgRatio = 1.0f;
	private int      m_bgBmpWidth = 0;
	private int      m_bgBmpHeight = 0;

	private int mBookOriginalW;
	private int mBookOriginalH;
	private int mSceenWidth;
	private int mSceenHeight;
	private ArrayList<Bitmap> mForeBitmapList;
	private ArrayList<Rect> mForeBitmapRectList;

	private ArrayList<Bitmap> mKokForeBitmapList;

	private Paint m_pt = new android.graphics.Paint(Paint.DITHER_FLAG);
	private float m_fratio_init = 1.0f;
	private int m_iviewXoffset_init = 0;
	private int m_iviewYoffset_init = 0;

    //private NewContainerView mParentLayout;

    private Bitmap mHotRegionStopBmp = null;
    private Bitmap mHotRegionPlay1Bmp = null;
    private Bitmap mHotRegionPlay2Bmp = null;

    private int       mCurHotRegionIndex = -1;
    private Timer m_tmHotRegion = null;
    private TimerTask m_ttHotRegionTask = null;
    private int       mSpeakerWidth = 0;
    private int       mSpeakerHeight = 0;



    /**
     * 初始化状态常量
     */
    private static final int STATUS_INIT = 1;

    /**
     * 图片放大状态常量
     */
    private static final int STATUS_ZOOM_OUT = 2;

    /**
     * 图片缩小状态常量
     */
    private static final int STATUS_ZOOM_IN = 3;

    /**
     * 图片拖动状态常量
     */
    private static final int STATUS_MOVE = 4;
    /**
     * 图片拖动或缩放完后的状态
     */
    private static final int STATUS_IDLE = 5;
    private   int       mCurrentStatus =  STATUS_INIT;
    /**
     * 记录上次两指之间的距离
     */
    private double lastFingerDis;
    /**
     * 记录上次手指移动时的横坐标
     */
    private float lastXMove = -1;

    /**
     * 记录上次手指移动时的纵坐标
     */
    private float lastYMove = -1;
    /**
     * 记录手指在横坐标方向上的移动距离
     */
    private float movedDistanceX;

    /**
     * 记录手指在纵坐标方向上的移动距离
     */
    private float movedDistanceY;

    /**
     * 记录canvas的宽。
     */
    private int canvasWidth;
    /**
     * 记录canvas的高。
     */
    private int canvasHeight;
    /**
     * 记录当前图片的宽度，图片被缩放时，这个值会一起变动
     */
    private float currentBitmapWidth;

    /**
     * 记录当前图片的高度，图片被缩放时，这个值会一起变动
     */
    private float currentBitmapHeight;
    /**
     * 记录手指移动的距离所造成的缩放比例
     */
    private float scaledRatio;
    /**
     * 记录两指同时放在屏幕上时，中心点的横坐标值
     */
    private float centerPointX;

    /**
     * 记录两指同时放在屏幕上时，中心点的纵坐标值
     */
    private float centerPointY;

    private boolean mKokCompleted = false;

    private int   mSpeed;
    private  float mSpeedRatio;

    public NewBookPageView(Context context) {
        super(context);
        init(context);
    }

    public NewBookPageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public NewBookPageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public void recycle() {
        m_showDictTopbarHandler.removeMessages(1);
        m_showDictTopbarHandler.removeMessages(2);

        bitmapback_recycle();
        bitmapfore_recycle();
        bitmapkokfore_recycle();

        hotRegionBitmapRecycle();

        m_dr = null;
        synchronized(this){
            m_lastkokunitposforonefile = -1;
            m_alrckok.clear();
        }
        if(null != m_alkokfiletimeregions){
            m_alkokfiletimeregions.clear();
            m_alkokfiletimeregions = null;
        }
        if (null != mForeBitmapRectList) {
            mForeBitmapRectList.clear();
            mForeBitmapRectList = null;
        }
        if (m_alrckokOnDraw != null) {
            int size = m_alrckokOnDraw.length;
            for (int i = 0; i < size; i++) {
                m_alrckokOnDraw[i] = null;
            }
            m_alrckokOnDraw = null;
        }

        //System.gc();
    }

    public void setmutualactioncallback(Imutualaction callback, int ikokcolor, Devicescreenbasicinfo dsi, int ireadtype) {
        m_mutualactioncallback = callback;
        m_ikokcolor = ikokcolor;
        m_dsi = dsi;
        m_ireadtype = ireadtype;
        LightingColorFilter cf = new LightingColorFilter(Color.TRANSPARENT,  m_ikokcolor);

        m_ptkok.setColorFilter(cf);
        m_ptkok.setAntiAlias(true);
        m_pt.setStyle(Paint.Style.FILL);
        m_pt.setStyle(Paint.Style.FILL);
        m_pt.setAntiAlias(true);

        if(null != m_mutualactioncallback) {
            int istatus = m_mutualactioncallback.getpinyinenglishshow();
            m_ishowpinyin = istatus & 0x01;
            m_ishowanotherlan = istatus & 0x02;
        }
    }

    public void setbooknetid(int inetid) {
        m_inetid = inetid;
    }

    public void setbookid(int ibookid) {
        m_ibookid = ibookid;
    }

    public void setinnerpage(int iinnerpage, Pagedata pd, int iviewXoffset, int iviewYoffset){
        mCurHotRegionIndex = -1;
        if((m_iinnerpage == iinnerpage && null != m_pd) || iinnerpage < 0) {
            return;
        }
        m_iinnerpage = iinnerpage;
        m_pd = pd;
        if(null == m_pd) {
            // {"id":51,"name":"大蛋糕","desc":"","grade":"Grade 2","thumb":"http://10.135.195.180:8086/tushu/thumb/81082.jpg","setting":{"py":1,"en":0,"tl":0},"edition":1,"original_id":"81082","pages":12,"pages_read":0,"whole_pages":15,....}
            // the real "pages" is 11 and the real "whole_pages" is 14
            return;
        }


        hotRegionBitmapRecycle();
        if (m_pd.getHotRegionData() != null && m_pd.getHotRegionData().size() > 0) {

            //mHotRegionStopBmp = ((BitmapDrawable)getResources().getDrawable(R.raw.speaker_stop)).getBitmap();
            mHotRegionStopBmp = BitmapFactory.decodeResource(getResources(), R.raw.speaker_stop);

            //mHotRegionPlay1Bmp = ((BitmapDrawable)getResources().getDrawable(R.raw.speaker_play1)).getBitmap();
            mHotRegionPlay1Bmp = BitmapFactory.decodeResource(getResources(), R.raw.speaker_play1);
            //mHotRegionPlay2Bmp = ((BitmapDrawable)getResources().getDrawable(R.raw.speaker_play2)).getBitmap();
            mHotRegionPlay2Bmp = BitmapFactory.decodeResource(getResources(), R.raw.speaker_play2);
            mSpeakerWidth = (int)getResources().getDimension(R.dimen.speaker_btn_width);
            mSpeakerHeight = (int)getResources().getDimension(R.dimen.speaker_btn_height);
        }
        m_iviewXoffset = iviewXoffset;
        m_iviewYoffset = iviewYoffset;
        m_iviewXoffset_init = iviewXoffset;
        m_iviewYoffset_init = iviewYoffset;


        setBackgroundResource(0);
        if(null != m_bmpBkg) {
            bitmapback_recycle();
        }
        bitmapfore_recycle();
        //加载当前页的背影图（根据条件判断是否显示  拼音、英文）
        showbookimage();
        //初始走红相关
        initDictregionKokregion();
        //准备前景图
        if (mForeBitmapList == null || mForeBitmapList.size() <= 0) {
            mForeBitmapList = safegenerateForeBimapList(false, m_pd.getEnglishPage());
        }
       //准备前景图位置信息
        if (mForeBitmapRectList == null || mForeBitmapRectList.size() <= 0) {
            mForeBitmapRectList = getForeBimapRectList(m_pd.getEnglishPage());
        }
       //如果是封皮准备书名语音
        initTitleMp3();


    }

    private void initTitleMp3() {
        m_closekokimmediately.set(false);
        if (m_iinnerpage == 0) {
            if(null != m_pd) {
                {
                    String titlemp3path  = m_pd.getTitleMp3();
                    if (!TextUtils.isEmpty(titlemp3path)) {
                        File titilemp3file = new File(titlemp3path);
                        if (titilemp3file != null && titilemp3file.exists() && titilemp3file.isFile()) {
                            boolean haveconvertfiles = true;
                            String fasttitlepath = titlemp3path.substring(0, titlemp3path.length() - 2) + "_fast.wav";
                            File newfile = new File(fasttitlepath);
                            if (newfile != null && newfile.exists() && newfile.isFile()) {

                            } else {
                                m_mutualactioncallback.addSpeedConvertTask(m_iinnerpage, titlemp3path, 0, 1, DefaultSettings.SPEED_FAST, m_ibookid);
                            }

                            String slowtitlepath = titlemp3path.substring(0, titlemp3path.length() - 2) + "_slow.wav";
                            newfile = new File(slowtitlepath);
                            if (newfile != null && newfile.exists() && newfile.isFile()) {

                            } else {
                                m_mutualactioncallback.addSpeedConvertTask(m_iinnerpage, titlemp3path, 0, 1, DefaultSettings.SPEED_SLOW, m_ibookid);
                                haveconvertfiles = false;
                            }
                            if  (haveconvertfiles) {
                                m_mutualactioncallback.setSupportSpeecConvert(0, TextUtils.isEmpty(titlemp3path)?"no title file ":titlemp3path, m_ibookid);
                            }
                        }
                    }
                }
            }
        }

    }

    public void setinnerpage(int iinnerpage, Pagedata pd, int iviewXoffset, int iviewYoffset, boolean bautokok){
        setinnerpage(iinnerpage, pd, iviewXoffset, iviewYoffset);
        Message msg = new Message();
        msg.what = 0;
        msg.arg1 = bautokok ? 1 : 0;
        msg.arg2 = iinnerpage;
        m_hbookreaderReceiver.sendMessage(msg);
    }

    public void waitinnerpageloading(int iinnerpage, int iviewXoffset, int iviewYoffset) {
        m_iviewXoffset = iviewXoffset;
        m_iviewYoffset = iviewYoffset;
        m_iviewXoffset_init = iviewXoffset;
        m_iviewYoffset_init = iviewYoffset;
        if(null != m_bmpBkg) {
            bitmapback_recycle();
        }
        bitmapfore_recycle();
    }

    public boolean setplaykok(boolean bplaykok){
        return postkokrequest(bplaykok, ms_imsgplaykok, m_iinnerpage);
    }

    public boolean setautokok(boolean bplaykok, int iplaypagepos) {
		return postkokrequest(bplaykok, ms_imsgautokok, iplaypagepos);
	}

    public void requestClosePlaykokProcess() {
        //MyLog.d("logautokok requestClosePlaykokProcess");
        m_hdokoksound.sendEmptyMessage(ms_imsgstopkok);
    }

    public boolean starthotkok(int hotregionindex) {
        if (m_pd != null) {
            HotRegionData data = m_pd.getHotRegionData().get(hotregionindex);
            mCurHotRegionIndex = hotregionindex;
            return postkokrequest(m_iinnerpage, data.mIndexes);
        }
        return false;
    }


	public void setShowPinyinAnotherLan(int ipinyin_anotherlan_show){
	   	if(ipinyin_anotherlan_show != (m_ishowpinyin | m_ishowanotherlan)) {
	   		m_ishowpinyin = ipinyin_anotherlan_show & 0x01;
            m_ishowanotherlan = ipinyin_anotherlan_show & 0x02;
			if(null != m_bmpBkg) {
				bitmapback_recycle();
			}
	   	}
		showbookimage();
	}

	public void setkokplayable(boolean bplayable){
		m_closekokimmediately.set(!bplayable);
	}

	public void setratio(float fratio, int iratiodecode, int orignalW, int orignalH) {
		m_fratio = fratio;
		m_fratio_init = fratio;
		m_idecoderatio = iratiodecode;
		mBookOriginalW = orignalW;
		mBookOriginalH = orignalH;

		DisplayMetrics dm = new DisplayMetrics();
	    ((Activity)m_ct).getWindowManager().getDefaultDisplay().getMetrics(dm);
	    mSceenWidth = dm.widthPixels;
	    mSceenHeight = dm.heightPixels;
	}

    public void closeplaykokprocessimmediately() {
        m_closekokimmediately.set(true);
        closeplaykokprocess();
    }

    public void recordselectedpage(boolean bselected) {
        m_bselected.set(bselected);
        TLog.log("Activities NewReadBookActivity recordselectedpage " + m_iinnerpage + " " + bselected);
    }

    @Override
    public void onDetachedFromWindow(){
        m_closekokimmediately.set(true);
        closeplaykokprocess();
        //recycle();
        super.onDetachedFromWindow();
    }


/*
	@Override
	public boolean onTouchEvent(MotionEvent event)  {
		switch(event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			m_imovestartX = (int)event.getRawX();
			m_imovestartY = (int)event.getRawY();
			return true;
		case MotionEvent.ACTION_MOVE:
			return true;
		case MotionEvent.ACTION_UP:
			boolean bexcpetion = true;
			if(ConstValues.BOOKREADTYPE_READMYSELF == m_ireadtype) {

				int ix = (int)event.getX();
				int iy = (int)event.getY();
				if(null != m_dr && null != m_mutualactioncallback) {

					int x1 = ix - m_iviewXoffset;
					int y1 = iy - m_iviewYoffset;

					DictData dd = m_dr.getdictdata(new Point(ix - m_iviewXoffset, iy - m_iviewYoffset), m_fratio);
					if(null != dd) {
						if(System.currentTimeMillis() - m_llasttimeworddictshow <= 500) {
							break;
						}
						bexcpetion = false;
						m_llasttimeworddictshow = System.currentTimeMillis();
						m_mutualactioncallback.getdictionarydescription(m_ibookid, m_inetid, dd.m_sdictword, dd.m_sdictpinyin);
					}
					else{
					}
				}
			}
			if(bexcpetion) {
				m_mutualactioncallback.bookpageviewonTouch(MotionEvent.ACTION_POINTER_ID_SHIFT, -9999, -9999);
				m_imoveendX = (int)event.getRawX();
				m_imoveendY = (int)event.getRawY();
				m_mutualactioncallback.bookpageviewonTouchMove(m_imovestartX, m_imovestartY, m_imoveendX, m_imoveendY);
			}
			break;
		}
		return super.onTouchEvent(event);
	}
*/


    private boolean mBeingTouched = false;
    private  long  mLastDownTime = 0;
    private  float  mLastDownX = 0f;
    private  float  mLastDownY = 0f;
    private  boolean  mHaveSendUmsEvent = false;


    private class  WordDictMsgObj {
        public int x;
        public  int y;
        public DictData dd;
    };

    private class  WordEnDictMsgObj {
        public int x;
        public  int y;
        public EnDictData dd;
    };


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:

                //m_imovestartX = (int)event.getRawX();
                //m_imovestartY = (int)event.getRawY();

                float x = event.getX();
                float y = event.getY();
                long curtime = System.currentTimeMillis();

                mHaveSendUmsEvent = false;

                mBeingTouched = true;
                if (curtime - mLastDownTime < 300) {
                    if (distanceBetweenDownEvent(x, y, mLastDownX, mLastDownY) < 40.0f) {
                        m_showDictTopbarHandler.removeMessages(1);
                        m_showDictTopbarHandler.removeMessages(2);
                        //m_mutualactioncallback.hideTransOrDict();

                        backToInitStatus();


                        mLastDownX = 0;
                        mLastDownY = 0;
                        mLastDownTime = 0;

                        return true;
                    }
                }
                mLastDownX = x;
                mLastDownY = y;
                mLastDownTime = curtime;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                if (event.getPointerCount() == 2) {
                    // 当有两个手指按在屏幕上时，计算两指之间的距离
                    lastFingerDis = distanceBetweenFingers(event);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                float xMove = event.getX();
                float yMove = event.getY();



                if (event.getPointerCount() == 1) {
                    // 只有单指按在屏幕上移动时，为拖动状态

                    if (lastXMove == -1 && lastYMove == -1) {
                        lastXMove = xMove;
                        lastYMove = yMove;
                    }
                    //currentStatus = STATUS_MOVE;
                    movedDistanceX = xMove - lastXMove;
                    movedDistanceY = yMove - lastYMove;
                    // 进行边界检查，不允许将图片拖出边界

                    if (m_iviewXoffset > 0) {
                        movedDistanceX = 0;
                    } else if  (m_iviewXoffset + movedDistanceX > 0) {
                        movedDistanceX = - m_iviewXoffset;
                    } else if (canvasWidth - (m_iviewXoffset + movedDistanceX) > currentBitmapWidth) {
                        movedDistanceX = 0;
                    }

                    if (m_iviewYoffset > 0) {
                        movedDistanceY = 0;
                    } else if ((m_iviewYoffset + movedDistanceY) > 0) {
                        movedDistanceY = - m_iviewYoffset;
                    } else if (canvasHeight - (m_iviewYoffset + movedDistanceY) > currentBitmapHeight) {
                        movedDistanceY = 0;
                    }

                    lastXMove = xMove;
                    lastYMove = yMove;

                    if ((movedDistanceX == 0 && movedDistanceY == 0) || m_fratio <= m_fratio_init) {
                        mCurrentStatus = STATUS_IDLE;
                        return true;
                    } else {
                        mCurrentStatus = STATUS_MOVE;
                        move();
                    }
                    // 调用onDraw()方法绘制图片
                    postInvalidate();

                } else if (event.getPointerCount() == 2) {
                    // 有两个手指按在屏幕上移动时，为缩放状态

                    centerPointBetweenFingers(event);
                    double fingerDis = distanceBetweenFingers(event);
                    if (fingerDis > lastFingerDis) {
                        if (m_fratio < 2 * m_fratio_init) {
                            mCurrentStatus = STATUS_ZOOM_OUT;
                            if (!mHaveSendUmsEvent) {
                                UmsAgent.onEvent(m_ct, "Page_zoom");
                                mHaveSendUmsEvent = true;
                            }
                            m_mutualactioncallback.hideTopBottomBarForScale();
                            m_mutualactioncallback.setViewPagerCanTurning(false);

                        } else {

                            mCurrentStatus = STATUS_IDLE;
                            lastFingerDis = fingerDis;
                            return true;
                        }
                    } else {
                        if (m_fratio > m_fratio_init) {
                            mCurrentStatus = STATUS_ZOOM_IN;
                            if (!mHaveSendUmsEvent) {
                                UmsAgent.onEvent(m_ct, "Page_zoom");
                                mHaveSendUmsEvent = true;
                            }
                            m_mutualactioncallback.hideTopBottomBarForScale();
                            m_mutualactioncallback.setViewPagerCanTurning(false);

                        } else {
                            mCurrentStatus = STATUS_IDLE;
                            lastFingerDis = fingerDis;

                            return true;
                        }
                    }
                    // 进行缩放倍数检查，最大只允许将图片放大2倍，最小可以缩小到初始化比例
                    if ((mCurrentStatus == STATUS_ZOOM_OUT && m_fratio < 2 * m_fratio_init)
                            || (mCurrentStatus == STATUS_ZOOM_IN && m_fratio > m_fratio_init)) {
                        scaledRatio = (float) (fingerDis / lastFingerDis);
                        float temp_m_fratio = m_fratio * scaledRatio;
                        if (temp_m_fratio > 2 * m_fratio_init) {
                            scaledRatio = 2 * m_fratio_init / m_fratio;
                            m_fratio = 2 * m_fratio_init;
                        } else if (temp_m_fratio < m_fratio_init) {
                            scaledRatio = m_fratio_init / m_fratio_init;

                            m_fratio = m_fratio_init;
                        } else {
                            m_fratio = temp_m_fratio;
                        }
                        // 调用onDraw()方法绘制图片
                        zoom();
                        postInvalidate();
                        lastFingerDis = fingerDis;
                    }
                    lastXMove = -1;
                    lastYMove = -1;
                } else {  // event.getPointerCount() > 2
                    lastXMove = -1;
                    lastYMove = -1;
                }
                break;
            case MotionEvent.ACTION_POINTER_UP:

                if (event.getPointerCount() == 2) {
                    // 手指离开屏幕时将临时值还原
                    lastXMove = -1;
                    lastYMove = -1;
                    mCurrentStatus = STATUS_IDLE;
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:

                // 手指离开屏幕时将临时值还原
                lastXMove = -1;
                lastYMove = -1;
                mCurrentStatus = STATUS_IDLE;


                if ((mCurrentStatus == STATUS_INIT || mCurrentStatus == STATUS_IDLE) && m_fratio <= m_fratio_init) {
                    if (m_mutualactioncallback != null) m_mutualactioncallback.setViewPagerCanTurning(true);
                } else {
                    if (m_mutualactioncallback != null) m_mutualactioncallback.setViewPagerCanTurning(false);
                }

                mBeingTouched = false;
                if (mKokCompleted && m_mutualactioncallback != null) {
                    backToInitStatus();
                    m_mutualactioncallback.playkokcompleted(true);
                }

                float up_x = event.getX();
                float up_y = event.getY();
                long uptime = System.currentTimeMillis();

                boolean bexcpetion = true;

                if (uptime - mLastDownTime < 500) {
                    if (distanceBetweenDownEvent(up_x, up_y, mLastDownX, mLastDownY) < 40.0f) {

                        if(DefaultSettings.BOOKREADTYPE_READMYSELF == m_ireadtype) {

                            int ix = (int)event.getX();
                            int iy = (int)event.getY();
                            if(null != m_dr && null != m_mutualactioncallback) {

                                int x1 = ix - m_iviewXoffset;
                                int y1 = iy - m_iviewYoffset;
                                int hotRegionIndex = getHotRegionIndex(new Point(ix - m_iviewXoffset, iy - m_iviewYoffset), m_fratio);
                                if (hotRegionIndex >= 0) {

                                    Message msg = m_playHotRegionHandler.obtainMessage(0, m_iinnerpage, hotRegionIndex);
                                    //starthotkok(m_iinnerpage, hotRegionData.mIndexes);
                                    m_playHotRegionHandler.sendMessage(msg);
                                    bexcpetion = false;
                                } else {
                                    if (m_pd.getEnglishPage()) {
                                        EnDictData dd = m_dr.getEnDictData(new Point(ix - m_iviewXoffset, iy - m_iviewYoffset), m_fratio);
                                        if (null != dd) {

                                            if (System.currentTimeMillis() - m_llasttimeworddictshow <= 500) {
                                                break;
                                            }
                                            bexcpetion = false;
                                            m_llasttimeworddictshow = System.currentTimeMillis();
                                            UmsAgent.onEvent(m_ct, "Page_getword_clk");
                                            WordEnDictMsgObj obj = new WordEnDictMsgObj();
                                            obj.x = ix;
                                            obj.y = iy;
                                            obj.dd = dd;
                                            Message msg = m_showDictTopbarHandler.obtainMessage(3, m_ibookid, m_inetid, obj);
                                            m_showDictTopbarHandler.sendMessageDelayed(msg, 310);
                                            //m_mutualactioncallback.getdictionarydescription(m_ibookid, m_inetid, dd.m_sdictword, dd.m_sdictpinyin);
                                        }
                                    } else {
                                        DictData dd = m_dr.getdictdata(new Point(ix - m_iviewXoffset, iy - m_iviewYoffset), m_fratio);
                                        if (null != dd) {

                                            if (System.currentTimeMillis() - m_llasttimeworddictshow <= 500) {
                                                break;
                                            }
                                            bexcpetion = false;
                                            m_llasttimeworddictshow = System.currentTimeMillis();
                                            UmsAgent.onEvent(m_ct, "Page_getword_clk");
                                            WordDictMsgObj obj = new WordDictMsgObj();
                                            obj.x = ix;
                                            obj.y = iy;
                                            obj.dd = dd;
                                            Message msg = m_showDictTopbarHandler.obtainMessage(1, m_ibookid, m_inetid, obj);
                                            m_showDictTopbarHandler.sendMessageDelayed(msg, 310);
                                            //m_mutualactioncallback.getdictionarydescription(m_ibookid, m_inetid, dd.m_sdictword, dd.m_sdictpinyin);
                                        }
                                    }
                                }

                            }
                        }
                        if(bexcpetion) {
                            m_showDictTopbarHandler.sendEmptyMessageDelayed(2, 310);
                            //m_mutualactioncallback.bookpageviewonTouch(MotionEvent.ACTION_POINTER_ID_SHIFT, -9999, -9999);
                            //m_imoveendX = (int)event.getRawX();
                            //m_imoveendY = (int)event.getRawY();
                        }
                    }
                }
                break;
            default:
                break;
        }

        return true;
    }

    private Handler m_playHotRegionHandler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            switch(msg.what) {
                case 0:
                    m_mutualactioncallback.hotRegionBtnClicked(msg.arg1, msg.arg2);
                    break;
                case 1:
                    break;
            }

        }
    };

    private Handler m_showDictTopbarHandler = new Handler() {
        @Override
        public void handleMessage(Message msg){
            switch(msg.what) {
                case 1:
                {
                    int bookid = msg.arg1;
                    int netid = msg.arg2;
                    WordDictMsgObj msgobj = (WordDictMsgObj)msg.obj;
                    DictData dd = (DictData)msgobj.dd;
                    m_mutualactioncallback.getdictionarydescription(m_ibookid, m_inetid, dd.m_sdictword, dd.m_sdictpinyin, msgobj.x, msgobj.y);
                }
                break;
                case 2:
                    m_mutualactioncallback.bookpageviewonTouch(MotionEvent.ACTION_POINTER_ID_SHIFT, -9999, -9999, m_fratio > m_fratio_init);
                    break;
                case 3:
                {
                    int bookid = msg.arg1;
                    int netid = msg.arg2;
                    WordEnDictMsgObj msgobj = (WordEnDictMsgObj)msg.obj;
                    EnDictData dd = (EnDictData)msgobj.dd;
                    m_mutualactioncallback.getDictionaryEnDescription(m_ibookid, m_inetid, dd, msgobj.x, msgobj.y);
                }
                break;
            }
        }
    };

   /*
   @Override
   	protected void onDraw(Canvas canvas)  {
       	super.onDraw(canvas);
       	if (m_bmpBkg == null) {
       		return;
       	}

       	switch (mCurrentStatus) {
    	case STATUS_ZOOM_OUT:
		case STATUS_ZOOM_IN:
			zoom();
		case STATUS_MOVE:
			move();
			break;
		default:
			break;
       	}
   		Rect bgdst = new Rect(m_iviewXoffset, m_iviewYoffset,
   				                          (int)(m_iviewXoffset + m_bgBmpWidth * m_fratio),
   		                                  (int)(m_iviewYoffset + m_bgBmpHeight * m_fratio));
   		canvas.drawBitmap(m_bmpBkg, null, bgdst, null);
   		bgdst = null;
       	if (mForeBitmapList == null) {
       		return;
       	}
       	int len = mForeBitmapList.size();

		if(null == m_tmkok || null == m_ttkoktask ) {
            if (len > 0) {
            	for(int i = 0; i < len; i++) {
            		Rect bmrc = mForeBitmapRectList.get(i);
            		Rect dst = maptoforegroundRegion(bmrc);
                    canvas.drawBitmap(mForeBitmapList.get(i),  null,  dst, null);
                    dst = null;
            	}
            }
			return;
		}
        try{
        	int isize = 0;
        	synchronized(this){
            	isize = m_alrckok.size();
            	if(isize > 0) {
                	for(int i = 0; i < isize; i++) {
                		//m_alrckokOnDraw[i] = new Rect(m_alrckok.get(i));

                		m_alrckokOnDraw[i].left = m_alrckok.get(i).left;
            	    	m_alrckokOnDraw[i].top = m_alrckok.get(i).top;
            	     	m_alrckokOnDraw[i].right = m_alrckok.get(i).right;
            		    m_alrckokOnDraw[i].bottom = m_alrckok.get(i).bottom;
                    }
            	}
        	}


        	for(int i = 0; i < len; i++) {
        		if(m_closekokimmediately.get()) {
        			break;
        		}
        		Rect bmrc = mForeBitmapRectList.get(i);
        		Rect dst = maptoforegroundRegion(bmrc);
        		Rect kokrc = m_alrckokOnDraw[i];
        		if (kokrc.width() > 0 || kokrc.height() > 0) {
	            	if (kokrc.right < bmrc.right) {
	            		Rect dst1 = new Rect();

	            		dst1.left = (int)(bmrc.left * m_fratio);
	            		dst1.top = (int)(bmrc.top * m_fratio);
	            		dst1.right = (int)((bmrc.left + kokrc.right - kokrc.left) * m_fratio);
	            		dst1.bottom = (int)(bmrc.bottom  * m_fratio);

	            		Rect dst2 = new Rect(dst1);

	            		dst2.left = dst1.right;
	            		dst2.right = (int)((bmrc.left + bmrc.right - bmrc.left) * m_fratio);

	            		dst1.left += m_iviewXoffset;
	            		dst1.right += m_iviewXoffset;
	            		dst1.top += m_iviewYoffset;
	            		dst1.bottom += m_iviewYoffset;

	            		dst2.left += m_iviewXoffset;
	            		dst2.right += m_iviewXoffset;
	            		dst2.top += m_iviewYoffset;
	            		dst2.bottom += m_iviewYoffset;


	            		canvas.save();
	            		canvas.clipRect(dst2);
	            		canvas.drawBitmap(mForeBitmapList.get(i),  null,  dst, null);
	            		canvas.restore();
	            		canvas.save();
	            		canvas.clipRect(dst1);
	            		//canvas.drawBitmap(mForeBitmapList.get(i),  src1,  dst1, m_ptkok);
	            		canvas.drawBitmap(mForeBitmapList.get(i),  null,  dst, m_ptkok);
	            		canvas.restore();

	            		dst1 = null;
	            		dst2 = null;

	            	} else {
	                    canvas.drawBitmap(mForeBitmapList.get(i),  null,  dst, m_ptkok);
	            	}
        		} else {
        			canvas.drawBitmap(mForeBitmapList.get(i),  null,  dst, null);
        		}

        		dst = null;
        	}


        }catch(java.lang.RuntimeException re) {
        	MyLog.de("BookPageView : onDraw : re : m_bmpchnfore = " + m_bmpchnfore);
        }catch(Exception e){

        }

	}

*/


   	protected void onDraw(Canvas canvas)  {
       	super.onDraw(canvas);
       	if (m_bmpBkg == null) {
       		return;
       	}
 /*      	switch (mCurrentStatus) {
    	case STATUS_ZOOM_OUT:
		case STATUS_ZOOM_IN:
			zoom();
            break;
		case STATUS_MOVE:
			move();
			break;
		default:
			break;
       	}

/*        if (mParentLayout != null) {
            mParentLayout.updataHotRegionButton(m_fratio, m_iviewXoffset, m_iviewYoffset);
        }*/

  		Rect bgdst = new Rect(m_iviewXoffset,  m_iviewYoffset,
   				                          (int)(m_iviewXoffset + m_bgBmpWidth * m_bgRatio *m_fratio),
   		                                  (int)(m_iviewYoffset + m_bgBmpHeight * m_bgRatio *  m_fratio));

   		canvas.drawBitmap(m_bmpBkg, null, bgdst, null);
   		bgdst = null;

       	if (mForeBitmapList == null) {
       		return;
       	}



        Bitmap hotregionbmp = null;

        int len = mForeBitmapList.size();
        int curhotreginindex = -1;

		if(null == m_tmkok || null == m_ttkoktask ) {
            if (len > 0) {
                for(int i = 0; i < len; i++) {
                    Rect bmrc = mForeBitmapRectList.get(i);
                    Rect dst = maptoforegroundRegion(bmrc);
                    canvas.drawBitmap(mForeBitmapList.get(i),  null,  dst, null);
                    dst = null;
                }
            }

            hotregionbmp = mHotRegionStopBmp;
            curhotreginindex = -1;
            //return;
        } else {

            if (mHotRegionPlay1) {
                hotregionbmp = mHotRegionPlay1Bmp;
            } else {
                hotregionbmp = mHotRegionPlay2Bmp;
            }
            curhotreginindex = mCurHotRegionIndex;
        }

        ArrayList<HotRegionData> hotRegionDataList = m_pd.getHotRegionData();
        if (hotRegionDataList != null && hotRegionDataList.size() > 0) {
            int hot_number = hotRegionDataList.size();
            for (int i = 0; i < hot_number; i++) {
                HotRegionData data = hotRegionDataList.get(i);
                if (data != null) {
                    Rect dstrect = new Rect();

                    dstrect.left = m_iviewXoffset + (int)((data.mCenterX) * m_fratio) - (int)(mSpeakerWidth * (m_fratio /(m_fratio_init * 2)));
                    dstrect.top = m_iviewYoffset + (int)((data.mCenterY) * m_fratio) - (int)(mSpeakerHeight * (m_fratio /(m_fratio_init * 2)));
                    dstrect.right = dstrect.left  + (int)(mSpeakerWidth * (m_fratio /m_fratio_init));
                    dstrect.bottom = dstrect.top + (int)(mSpeakerHeight * (m_fratio /m_fratio_init));

                    if (curhotreginindex == i) {

                        if (hotregionbmp != null && !hotregionbmp.isRecycled()) {
                            canvas.drawBitmap(hotregionbmp, null, dstrect, null);
                        }
                    } else {
                        if (mHotRegionStopBmp != null && !mHotRegionStopBmp.isRecycled()) {
                            canvas.drawBitmap(mHotRegionStopBmp, null, dstrect, null);
                        } else {
                            if (mHotRegionStopBmp == null) {
                                TLog.log("KOK mHotRegionStopBmp == null " + m_iinnerpage);
                            }
                            TLog.log("KOK missdraw mHotRegionStopBmp " + m_iinnerpage);
                        }
                    }
                }
            }
        }

        if (null == m_tmkok || null == m_ttkoktask) {
            return;
        }

        int isize = 0;
        synchronized(this){
            isize = m_alrckok.size();
            if(isize > 0) {
                for(int i = 0; i < isize; i++) {
                    //m_alrckokOnDraw[i] = new Rect(m_alrckok.get(i));
                    m_alrckokOnDraw[i].left = m_alrckok.get(i).left;
                    m_alrckokOnDraw[i].top = m_alrckok.get(i).top;
                    m_alrckokOnDraw[i].right = m_alrckok.get(i).right;
                    m_alrckokOnDraw[i].bottom = m_alrckok.get(i).bottom;

                }
               // MyLog.d("HotRegion ~~~~~~~~~~~~~~~~~~~ ");
            }
        }

        for(int i = 0; i < len; i++) {
            if(m_closekokimmediately.get()) {
                break;
            }
            int w = mForeBitmapRectList.get(i).width();
            int h =  mForeBitmapRectList.get(i).height();
            Rect bmrc = mForeBitmapRectList.get(i);
            Rect cndst = maptoforegroundRegion(bmrc);
            Rect kokrc = m_alrckokOnDraw[i];


            if (kokrc.width() > 0 || kokrc.height() > 0) {
                if (kokrc.right < bmrc.right) {

                    //Rect src1 = new Rect(0, 0, kokrc.right - kokrc.left, h);
                    Rect dst1 = maptoforegroundRegion(kokrc);

                    canvas.drawBitmap(mForeBitmapList.get(i),  null,  cndst, null);
                    canvas.save();
                    canvas.clipRect(dst1);
                    //canvas.drawBitmap(mKokForeBitmapList.get(i),  src1,  dst1, null);
                    canvas.drawBitmap(mKokForeBitmapList.get(i),  null,  cndst, null);
                    canvas.restore();
                    dst1 = null;
                } else {
                    canvas.drawBitmap(mForeBitmapList.get(i),  null,  cndst, null);
                    canvas.drawBitmap(mKokForeBitmapList.get(i),  null,  cndst, null);
                }
            } else {
                canvas.drawBitmap(mForeBitmapList.get(i),  null,  cndst, null);
            }

            cndst = null;
        }
    }

    private Handler m_hbookreaderReceiver = new Handler() {
        @Override
        public void handleMessage(Message msg){
            setautokok(1 == msg.arg1 ? true : false, msg.arg2);
        }
    };

    private Rect maptoforegroundRegion(Rect rc)  {
        Rect rcret = new Rect(rc);

        rcret.left = (int)(rcret.left * m_fratio + m_iviewXoffset);
        //rcret.right  = (int)(rcret.right * m_fratio + m_iviewXoffset);
        rcret.top  = (int)(rcret.top * m_fratio + m_iviewYoffset);
        //rcret.bottom  = (int)(rcret.bottom * m_fratio + m_iviewYoffset);
        rcret.right  = (int)(rcret.left * m_fratio + (rcret.right - rcret.left) * m_fratio +  m_iviewXoffset);
        rcret.bottom  = (int)(rcret.top * m_fratio + (rcret.bottom - rcret.top) * m_fratio + m_iviewYoffset);

        return rcret;
    }

    private void init(Context ct) {
        m_ct = ct;
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    private void bitmapback_recycle() {
        Bitmap bmp = m_bmpBkg;
        m_bmpBkg = null;
        try{
            if(bmp != null && !bmp.isRecycled()){
                bmp.recycle();
                bmp = null;
                TLog.log("KOK recycle backbitmap page " + m_iinnerpage);
               // MyLog.d("MyLog --- NewBookPageView : bitmapback_recycle : recycled");
            }
            System.gc();
        }catch(Exception e){
            TLog.log("KOK recycle backbitmap page " + m_iinnerpage + " e =  " + e);
            //MyLog.d("MyLog --- NewBookPageView : bitmapback_recycle : e : " + e);
        }
    }

    private void bitmapfore_recycle() {
        Bitmap bmp = m_bmpchnfore;
        m_bmpchnfore = null;
        try{
            if(bmp != null && !bmp.isRecycled()){
                bmp.recycle();
                bmp = null;
                TLog.log("MyLog --- BookPageView : bitmapfore_recycle : recycled");
            }
            if (mForeBitmapList != null && mForeBitmapList.size() > 0) {
                int size = mForeBitmapList.size();
                for (int i = 0; i < size; i++) {
                    Bitmap bm = mForeBitmapList.get(i);
                    if (bm != null) {
                        //MyLog.d("KOK recycle forbitmap page " +m_iinnerpage + " "+  i);
                        bm.recycle();
                    }
                }
                mForeBitmapList.clear();
                mForeBitmapList = null;
            }
            System.gc();
        }catch(Exception e){
            TLog.log("KOK recycle forbitmap page " + m_iinnerpage + "  e = " + e);
        }
    }

    private void hotRegionBitmapRecycle() {
        if (mHotRegionStopBmp != null) {
            if (!mHotRegionStopBmp.isRecycled()) {
                mHotRegionStopBmp.recycle();
                TLog.log("KOK recycle mHotRegionStopBmp " + m_iinnerpage);
            }
            mHotRegionStopBmp = null;
        }

        if (mHotRegionPlay1Bmp != null) {
            if (!mHotRegionPlay1Bmp.isRecycled()) {
                mHotRegionPlay1Bmp.recycle();
            }
            mHotRegionPlay1Bmp = null;
        }

        if (mHotRegionPlay2Bmp != null) {
            if (!mHotRegionPlay2Bmp.isRecycled()) {
                mHotRegionPlay2Bmp.recycle();
            }
            mHotRegionPlay2Bmp = null;
        }

    }

    private void bitmapkokfore_recycle() {

        if (mKokForeBitmapList != null && mKokForeBitmapList.size() > 0) {
            int size = mKokForeBitmapList.size();
            for (int i = 0; i < size; i++) {
                Bitmap bm = mKokForeBitmapList.get(i);
                if (bm != null) {
                    TLog.log("KOK recycle kokforbitmap page " + m_iinnerpage + " " + i);
                    bm.recycle();
                }
            }
            mKokForeBitmapList.clear();
            mKokForeBitmapList = null;
        }
        System.gc();

    }

    /**
     * 初始化走红：描红时间、位置
     */
    private void initDictregionKokregion() {
        m_closekokimmediately.set(false);
        if(null != m_pd) {
            if(null == m_dr) {
                m_dr = m_pd.getDictWordRegion();
            }
            if(null == m_alkokfiletimeregions || m_alkokfiletimeregions.size() <= 0) {
                KokRegion kr = m_pd.getKokRegion();
                if(null != kr) {
                    m_alkokfiletimeregions = new ArrayListtoNext<kokfilesoundregion>();
                    String[] saudiofiles = kr.getallaudiofilepathes();
                    if(null != saudiofiles) {
                        int i = 0;
                        int total_num = saudiofiles.length;
                        boolean support_speed_convert = true;
                        for(String sfile : saudiofiles){
                            if(!TextUtils.isEmpty(sfile)){
                                AudiofileTimeelapsedUnit[] koktimeranges = kr.getkokelapsedtimerangebyaudiofiles(sfile);
                                if(null != koktimeranges) {
                                    kokfilesoundregion ktr = new kokfilesoundregion(sfile, kr.getaudiofileTimeRange(sfile), koktimeranges);
                                    m_alkokfiletimeregions.add(ktr);
                                }
                                File file = new File(sfile);
                                String parentpath = file.getParent();
                                String filename = file.getName();
                                String convert_file_path = parentpath + File.separator + filename.substring(0, filename.length() - 2) + "_fast.wav";
                                File newfile = new File(convert_file_path);
                                if (newfile != null && newfile.exists() && newfile.isFile()) {

                                } else {
                                    //转换当前页的mp3 语速
                                    m_mutualactioncallback.addSpeedConvertTask(m_iinnerpage, sfile, i, total_num, DefaultSettings.SPEED_FAST, m_ibookid);
                                    support_speed_convert = false;
                                }
                                convert_file_path = parentpath + File.separator + filename.substring(0, filename.length() - 2) + "_slow.wav";
                                newfile = new File(convert_file_path);
                                if (newfile != null && newfile.exists() && newfile.isFile()) {
                                } else {
                                    m_mutualactioncallback.addSpeedConvertTask(m_iinnerpage, sfile, i, total_num, DefaultSettings.SPEED_SLOW, m_ibookid);
                                    support_speed_convert = false;
                                }

                            }
                            i++;
                        }
                        if (support_speed_convert) m_mutualactioncallback.setSupportSpeecConvert(m_iinnerpage, TextUtils.isEmpty(saudiofiles[0])? "no source file":saudiofiles[0], m_ibookid);
                    }
                    else{
                        //MyLog.d("NewBookPageView : initDictregionKokregion : NO VOICE!!!!");
                    }
                }
            }
        }
    }

    private boolean postkokrequest(int iplaypagepos, int[] bound) {
        if(null != m_pd.getKokRegion()) {
            Message msg = new Message();
            msg.what = ms_imsgplaykok;
            msg.arg1 = 1;
            msg.arg2 = iplaypagepos;
            msg.obj = bound;
            m_hdokoksound.sendMessage(msg);
            return true;
        }
        return false;
    }

    private boolean postkokrequest(boolean bplaykok, int imessagetype, int iplaypagepos) {
        if(!bplaykok) {
            if(m_bkokisplaying) {
                closeplaykokprocess();
            }
            Message msg = new Message();
            msg.what = ms_imsgplaykok;
            msg.arg1 = bplaykok ? 1 : 0;
            msg.arg2 = iplaypagepos;
            m_hdokoksound.sendMessage(msg);

            return true;
        }
        else{
            if(null == m_pd){
                return true; // for separated packages
            }
            if(m_bkokisplaying) {
                return false;
            }
            if(DefaultSettings.ms_Json_BookPageType_page == m_pd.getpageType()) {
                if(null != m_pd.getKokRegion()) {
                    Message msg = new Message();
                    msg.what = ms_imsgplaykok;
                    msg.arg1 = bplaykok ? 1 : 0;
                    msg.arg2 = iplaypagepos;
                    m_hdokoksound.sendMessage(msg);
                    return true;
                }
            } else if (DefaultSettings.ms_Json_BookPageType_cover == m_pd.getpageType()) {
                if (!TextUtils.isEmpty(m_pd.getTitleMp3())) {
                    Message msg = new Message();
                    msg.what = ms_imsgplaykok;
                    msg.arg1 = bplaykok ? 1 : 0;
                    msg.arg2 = iplaypagepos;
                    m_hdokoksound.sendMessage(msg);
                    return true;
                }
            }
        }
        return false;
    }

    private Handler m_hdokoksound = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(ms_imsgplaykok == msg.what || ms_imsgautokok == msg.what) {
                KokRegion kr = m_pd.getKokRegion();
                dokoksound(1 == msg.arg1, msg.what, kr, msg.arg2, (int[])msg.obj);
            } else if (ms_imsgstopkok == msg.what) {
                closeplaykokprocess();
            }
        }
    };

    private void dokoksound(boolean bplaykok, int imessagetype, KokRegion kr, int iplaypagepos, int[] bound) {
       // MyLog.d("logautokok dokoksound " + bplaykok);
        closeplaykokprocess();
        if(!bplaykok &&  null != m_mutualactioncallback) {
            if(ms_imsgplaykok == imessagetype) {
                m_mutualactioncallback.playkokcompleted(true);
            }
            else if(ms_imsgautokok == imessagetype) {
                m_mutualactioncallback.autokokcurrentpagecompleted();
            }
        }
        else{
            if (kr != null) {
                playallkokbysentenceorder(iplaypagepos, bound);
            } else if (!TextUtils.isEmpty(m_pd.getTitleMp3())) {
                playtitlemap3(iplaypagepos);
            }
        }
    }

    private void showbookimage() {
        String simgpath = null;
        int istatus = (m_ishowpinyin | m_ishowanotherlan);
        if(null != m_pd) {
            switch(istatus) {
                case 3: // both pinyin and english
                    simgpath = m_pd.getwgcnpyen();
                    break;
                case 2: // english
                    simgpath = m_pd.getwgcnen();
                    break;
                case 1: // pinyin
                    simgpath = m_pd.getwgcnpy();
                    break;
                default:
                    break;
            }
            if(null == simgpath){
                simgpath = m_pd.getwgcn();
            }
            else {
                File f = new File(simgpath);
                if(!f.exists() || !f.isFile()) {
                    simgpath = m_pd.getwgcn();
                }
            }
            if((m_ishowpinyin & 0x01) > 0 && (m_ishowanotherlan & 0x10) > 0){
                if(null == simgpath){
                    simgpath = m_pd.getwgcn();
                }
            }
        }


		if (m_bmpBkg == null) {
            m_bmpBkg = safegenerateBackgroundBitmap(simgpath, (int) (mBookOriginalW * 2 * m_fratio_init),
                    (int) (mBookOriginalH * 2 * m_fratio_init), (mSceenWidth > mSceenHeight) ? true : false);
            if (null != m_bmpBkg) {
                //setImageBitmap(m_bmpBkg);
                m_bgBmpWidth = m_bmpBkg.getWidth();
                m_bgBmpHeight = m_bmpBkg.getHeight();
                m_bgRatio = (float) mBookOriginalW / m_bgBmpWidth;
            }
        }

        postInvalidate();

    }




    public void setBackImageBitmap(Bitmap bitmap) {
		m_bmpBkg = null;
	}

	private Bitmap safegenerateBackgroundBitmap(String simgpath, int ideawWidth, int idrawheight, boolean land) {
        TLog.log("KOK gebackbitmap " + simgpath + " ideal " + ideawWidth + " " + idrawheight + " land = " + true);
		Bitmap bmp = null;

		if(null != simgpath) {
			try{
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inPreferredConfig = Bitmap.Config.RGB_565;
/*				if(utils.readdeviceheapgrowthlimit(m_ct) <= 96) {
					options.inSampleSize = Math.max(3, m_idecoderatio);
					options.inJustDecodeBounds = false;
				}*/
				//else{
					try{
						options.inJustDecodeBounds = true;
						ImageUtils.safedecodebitmapfile(simgpath, options);
						//MyLog.d("KOK gebackbitmap " + " ow = " + options.outWidth + " oh = " + options.outHeight);
						/*int igetmax = Math.max(options.outWidth, options.outHeight);
						int igetmin = Math.min(options.outWidth, options.outHeight);
						if(igetmax > 1338 || igetmin > 976) {
							int ishrink1 = (int)((float)igetmax / (float)1338 + 0.499f);
							int ishrink2 = (int)((float)igetmin / (float)976 + 0.499f);
							options.inSampleSize = Math.max(2, Math.max(ishrink1, ishrink2));
						}
						else{
							options.inSampleSize = 2;
						}*/
						if (land) {
							if (options.outHeight > idrawheight) {
								options.inSampleSize = 2;
							}
						} else {
							if (options.outWidth > ideawWidth) {
								options.inSampleSize = 2;
							}
						}
					}catch(Exception e){
					}
					options.inJustDecodeBounds = false;
				//}

				bmp = ImageUtils.safedecodebitmapfile(simgpath, options);

                if (bmp == null) {
                    TLog.log("KOK gebackbitmap == null  inSampleSize = " + options.inSampleSize);
                } else {

                  //  MyLog.d("KOK gebackbitmap inSampleSize = " + options.inSampleSize + " w = " + bmp.getWidth() + " h = " + bmp.getHeight());
                }

			}catch(Exception e){
                TLog.log("KOK gebackbitmap e = " + e);
			}catch(OutOfMemoryError oe){
                TLog.log("KOK gebackbitmap oe = " + oe);
			}
		}
		return bmp;
	}

    /**
     *
     * 生成卡拉Ok红色的前景图
     */
	private ArrayList<Bitmap> safegenerateForeBimapList(boolean kokbitmap, boolean isEnglishPage) {
		ArrayList<Bitmap> bplist = null;
		if(null != m_pd && !m_closekokimmediately.get()) {
			if (kokbitmap) {
                StringIntQuadruple[] list = null;
                if (!isEnglishPage) {
                    list = m_pd.getkokcnsimgs();
                } else{
                    list = m_pd.getkokensimgs();
                }

				if (list != null && list.length > 0) {
					for (StringIntQuadruple cninfo : list) {
						Bitmap bitmap = safegenerateForeBitmap(cninfo.m_sVal1);
						if (bitmap != null) {
							if (bplist == null) {
								bplist = new ArrayList<Bitmap>();
							}
							bplist.add(bitmap);
						}
					}
				}

			} else {
                if (!isEnglishPage) {
                    StringIntQuadruple[] cninfolist = m_pd.getcnsimgs();
                    ArrayList<StringIntQuadruple> list = m_pd.getcnsimglist();
                    if (list != null && list.size() > 0) {
                        for (StringIntQuadruple cninfo : list) {
                            Bitmap bitmap = safegenerateForeBitmap(cninfo.m_sVal1);
                            if (bitmap != null) {
                                if (bplist == null) {
                                    bplist = new ArrayList<Bitmap>();
                                }
                                bplist.add(bitmap);
                            }
                        }
                    }
                } else {
                    //StringIntQuadruple[] list = m_pd.getensimgs();
                    ArrayList<StringIntQuadruple> list = m_pd.getensimglist();
                    if (list != null && list.size() > 0) {
                        for (StringIntQuadruple eninfo : list) {
                            Bitmap bitmap = safegenerateForeBitmap(eninfo.m_sVal1);
                            if (bitmap != null) {
                                if (bplist == null) {
                                    bplist = new ArrayList<Bitmap>();
                                }
                                bplist.add(bitmap);
                            }
                        }
                    }
                }

			}
		}

		return bplist;
	}

	private ArrayList<Rect> getForeBimapRectList(boolean isEnglishPage) {
		ArrayList<Rect> rectlist = null;
		if(null != m_pd && !m_closekokimmediately.get()) {
            ArrayList<StringIntQuadruple> list = null;
            if (!isEnglishPage) {
                //StringIntQuadruple[] cninfolist = m_pd.getcnsimgs();
                list = m_pd.getcnsimglist();
            } else {
                list = m_pd.getensimglist();
            }
			if (list != null && list.size() > 0) {
				for (StringIntQuadruple cninfo : list) {
					if (cninfo != null) {
						Rect temp = new Rect(cninfo.m_iVal2, cninfo.m_iVal3,
								cninfo.m_iVal2 + cninfo.m_iVal4, cninfo.m_iVal3 + cninfo.m_iVal5);
						if (rectlist == null) {
							rectlist = new ArrayList<Rect>();
						}
						rectlist.add(temp);
					}
				}
			}
		}

		return rectlist;
	}

	private Bitmap safegenerateForeBitmap(String simgpath) {
        //MyLog.d("KOK getforbitmap " + simgpath);
		Bitmap bmp = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = Bitmap.Config.RGB_565;
		options.inJustDecodeBounds = false;
		bmp = ImageUtils.safedecodebitmapfile(simgpath, options);
		if (bmp != null) {
           // bmp.prepareToDraw();
		} else {
            TLog.log("KOK getforbitmap " + simgpath + " error!");
        }
		return bmp;
	}


	private void playtitlemap3(int iplaypagepos) {
		boolean bdone = false;
		String mp3 = m_pd.getTitleMp3();
		if (!TextUtils.isEmpty(mp3)) {
			File mp3file = new File(mp3);
			if (mp3file != null) {
				if (mp3file.exists() && mp3file.isFile()) {
					bdone = true;
				}
			}
		}
		if(bdone) {
			bdone = onlystartmediaplayer(mp3, iplaypagepos);
		}
		if(!bdone) {
			onlyclosemediaplayer();
			if(null != m_mutualactioncallback){
				m_mutualactioncallback.playkokcompleted(true);
			}
		}
	}

    /**
     * 启动语音和走红
     * @param iplaypagepos
     */
	//private float m_forebmpRatio = 1.0f;
	private void playallkokbysentenceorder(int iplaypagepos, int[] bound) {
//MyLog.dee("MyLog -------------- BookPageView : playallkokbysentenceorder : iplaypagepos = " + iplaypagepos);

/*		synchronized(this){
		    m_alrckok.clear();
		    //m_alrckokOnDraw = null;
		}*/
        //MyLog.d("logautokok playallkokbysentenceorder " + iplaypagepos);
        if (bound == null || bound.length <= 0) {
            mCurHotRegionIndex = -1;
        }
        if (m_alrckok != null) {
            m_alrckok.clear();
        }
        m_rckoklastdraw = null;

        if (m_alrckokOnDraw == null) {
            int size = 0;
            if (!m_pd.getEnglishPage()) {
                size = m_pd.getcnsimgsSize();
            } else {
                size = m_pd.getensimgsSize();
            }
            //MyLog.d("KOK playallkokbysentenceorder " +iplaypagepos + " new " + size );
            if (size > 0) {
                m_alrckokOnDraw = new Rect[size];
                for (int i = 0; i < size; i++ ) {
                    m_alrckokOnDraw[i] = new Rect(0, 0, 0, 0);
                }
            } else {
                //setplaykok(false);
                //return;
            }
        } else if (m_alrckokOnDraw.length > 0) {
            //MyLog.d("KOK playallkokbysentenceorder " +iplaypagepos + " old " + m_alrckokOnDraw.length );
            for (int i = 0; i < m_alrckokOnDraw.length; i++ ) {
                if (m_alrckokOnDraw[i] != null) {
                    m_alrckokOnDraw[i].left = 0;
                    m_alrckokOnDraw[i].top = 0;
                    m_alrckokOnDraw[i].right = 0;
                    m_alrckokOnDraw[i].bottom = 0;
                } else {
                    m_alrckokOnDraw[i] = new Rect(0, 0, 0, 0);
                }

            }
        }

        if(null == m_alkokfiletimeregions || m_alkokfiletimeregions.size() <= 0) {
            initDictregionKokregion();
        }

        if (bound != null && bound.length > 0) {
            if (m_alkokfiletimeregions != null && m_alkokfiletimeregions.size() > 0) {
                int sentence_number = m_alkokfiletimeregions.size();
                for (int i = 0; i < sentence_number; i++) {
                    if (i < bound[0]) {
                        int blocknumber = m_alkokfiletimeregions.get(i).blocknumber;
                        for (int j = 0; j < blocknumber; j++) {
                            m_alrckok.add(new Rect(0, 0, 0, 0));
                        }
                    } else {
                        break;
                    }
                }
            }
        }

        if(null == m_alkokfiletimeregions || m_alkokfiletimeregions.size() <= 0) {
            TLog.log("NewBookPageView : playallkokbysentenceorder :  null error!");
            setplaykok(false);
            return;
        }
        int idrawwidth = m_dsi.m_iScreenWidth - 2 * m_iviewXoffset;
        int idrawheight = m_dsi.m_iScreenHeight - 2 * m_iviewYoffset;

/*		if(null == m_bmpchnfore && null != m_pd){
			m_bmpchnfore = safegenerateForegroundBitmap(m_pd.getfgcn(), idrawwidth, idrawheight);
		}
		if(null == m_bmpchnfore) {
			MyLog.de("BookPageView : playallkokbysentenceorder :  foreground failed!");
			setplaykok(false);
			return;
		}
		*/

        if (mForeBitmapList == null || mForeBitmapList.size() <= 0) {
            mForeBitmapList = safegenerateForeBimapList(false, m_pd.getEnglishPage());
        }
        if (!m_pd.getEnglishPage()) {
            if (mForeBitmapList == null || mForeBitmapList.size() <= 0 || mForeBitmapList.size() != m_pd.getcnsimgsSize()) {
                //setplaykok(false);
                //return;
            }
        } else {
            if (mForeBitmapList == null || mForeBitmapList.size() <= 0 || mForeBitmapList.size() != m_pd.getensimgsSize()) {
                //setplaykok(false);
                //return;
            }
        }
        /**
         * 生成卡拉Ok红色的前景图
         */
        if (mKokForeBitmapList == null || mKokForeBitmapList.size() <= 0) {
            mKokForeBitmapList = safegenerateForeBimapList(true, m_pd.getEnglishPage());
        }
        if (!m_pd.getEnglishPage()) {
            if (mKokForeBitmapList == null || mKokForeBitmapList.size() <= 0 || mKokForeBitmapList.size() != m_pd.getcnsimgsSize()) {
                //setplaykok(false);
                //return;
            }
        } else {
            if (mKokForeBitmapList == null || mKokForeBitmapList.size() <= 0 || mKokForeBitmapList.size() != m_pd.getensimgsSize()) {
                //setplaykok(false);
                //return;
            }
        }

        if (mForeBitmapRectList == null || mForeBitmapRectList.size() <= 0) {
            mForeBitmapRectList = getForeBimapRectList(m_pd.getEnglishPage());
        }
        if (mForeBitmapRectList == null || mForeBitmapRectList.size() <= 0) {
            //setplaykok(false);
            //return;
        }

        m_alkokfiletimeregions.setBound(bound);
        kokfilesoundregion first = m_alkokfiletimeregions.getHead();
        boolean bdone = (null != first);
        if(bdone) {
            bdone = onlystartmediaplayer(first, iplaypagepos,bound != null && bound.length > 0);
    }
        if(!bdone) {
            closeplaykokprocess();
            if(null != m_mutualactioncallback){
                m_mutualactioncallback.playkokcompleted(true);
            }
        }
    }

    private boolean onlystartmediaplayer(String titlemp3, int iplaypagepos) {
/*        if(!m_bselected.get()){
            return false;
        }*/
        boolean bdone = true;
        try {
            synchronized(this) {
                bdone = createMediaPlayerForTitle(iplaypagepos);
                if(!bdone) {
                    return false;
                }

                File file = new File(titlemp3);
                String filepath = "";

                if (file != null && file.exists() && file.isFile()) {
                    filepath = file.getAbsolutePath();
                } else {
                    return false;
                }

                if (mSpeed == DefaultSettings.SPEED_SLOW) {
                    String slowfilepath = filepath.substring(0, filepath.length() - 2) + "_slow.wav";
                    File slowfile = new File(slowfilepath);
                    if (slowfile != null && slowfile.exists() && slowfile.isFile()) {
                        m_mpkokplayer.setDataSource(slowfilepath);
                    } else {
                        m_mpkokplayer.setDataSource(titlemp3);
                    }
                } else if (mSpeed == DefaultSettings.SPEED_FAST)  {
                    String fastfilepath = filepath.substring(0, filepath.length() - 2) + "_fast.wav";
                    File fastfile = new File(fastfilepath);
                    if (fastfile != null && fastfile.exists() && fastfile.isFile()) {
                        m_mpkokplayer.setDataSource(fastfilepath);
                    } else {
                        m_mpkokplayer.setDataSource(titlemp3);
                    }
                } else {
                    m_mpkokplayer.setDataSource(titlemp3);
                }
                m_mpkokplayer.prepare();
                m_mpkokplayer.start();
                m_bkokisplaying = true;
            }

        } catch (IllegalArgumentException e) {
            bdone = false;
        } catch (IllegalStateException e) {
            bdone = false;
        } catch (IOException e) {
            bdone = false;
        }
        if(!bdone) {
            onlyclosemediaplayer();
        }
        return bdone;
    }


    private boolean onlystartmediaplayer(kokfilesoundregion kfr, int iplaypagepos, boolean hotregion) {
        if(!m_bselected.get()){
            return false;
        }
//MyLog.dee("MyLog -------------- BookPageView : onlystartmediaplayer : iplaypagepos = " + iplaypagepos);
        boolean bdone = true;
        try {
            synchronized(this) {
                bdone = createnewmediaplayer(iplaypagepos);
                if(!bdone) {
                    return false;
                }
                File file = new File(kfr.m_saudiofilepath);
                String filepath = "";

                if (file != null && file.exists() && file.isFile()) {
                    filepath = file.getAbsolutePath();
                } else {
                    return false;
                }

                if (mSpeed == DefaultSettings.SPEED_SLOW) {
                    String slowfilepath = filepath.substring(0, filepath.length() - 2) + "_slow.wav";
                    File slowfile = new File(slowfilepath);
                    if (slowfile != null && slowfile.exists() && slowfile.isFile()) {
                        m_mpkokplayer.setDataSource(slowfilepath);
                    } else {
                        return false;
                    }


                } else if (mSpeed == DefaultSettings.SPEED_FAST)  {
                    String fastfilepath = filepath.substring(0, filepath.length() - 2) + "_fast.wav";
                    File fastfile = new File(fastfilepath);
                    if (fastfile != null && fastfile.exists() && fastfile.isFile()) {
                        m_mpkokplayer.setDataSource(fastfilepath);
                    } else {
                        return false;
                    }
                } else {
                    m_mpkokplayer.setDataSource(kfr.m_saudiofilepath);
                }
                m_mpkokplayer.prepare();
                TLog.log("Duration = " + m_mpkokplayer.getDuration());
                m_mpkokplayer.start();
                m_bkokisplaying = true;


            }
            IntDouble idu = kfr.m_iduaudiofiletimerange;
            if(null != idu){
				/*for(AudiofileTimeelapsedUnit unit : kfr.m_timeregions) {
					MyLog.di("time: (" + unit.m_iaudiocliptimebegin + ", " + unit.m_iaudiocliptimeend + ") : (" + unit.m_rc.left + ", " + unit.m_rc.top + ", " + unit.m_rc.right + ", " + unit.m_rc.bottom + ")");
				}*/
                startkoktextcolorchange(kfr.m_timeregions, idu.m_ival1, idu.m_ival2, hotregion);
                if (hotregion) starthotregiontimer();
            }
            else{
                TLog.log("NewBookPageView : onlystartmediaplayer : null error!");
            }
        } catch (IllegalArgumentException e) {
            bdone = false;
        } catch (IllegalStateException e) {
            bdone = false;
        } catch (IOException e) {
            bdone = false;
        }
        if(!bdone) {
            onlyclosemediaplayer();
        }
        return bdone;
    }

    private boolean createnewmediaplayer(int itag) {
//MyLog.dee("MyLog ------- BookPageView : createnewmediaplayer : itag = " + itag + ", m_iinnerpage = " + m_iinnerpage);
        closeplaykokprocess();
        m_mpkokplayer = new myMediaPlayer();
        m_mpkokplayer.settag(itag);
        try{
            m_mpkokplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if(m_mpkokplayer.gettag() != m_iinnerpage && m_iinnerpage >= 0) {
                        if(null != m_mpkokplayer) {
                            closeplaykokprocess();
                        }
                        return;
                    }
                }
            });

            m_mpkokplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if(!m_bkokisplaying) {

                        return;
                    }
                    int iplaypagepos = m_mpkokplayer.gettag();
                    if(m_mpkokplayer.gettag() != m_iinnerpage && m_iinnerpage >= 0) {
                        if(null != m_mpkokplayer) {
                            closeplaykokprocess();
                        }
                        return;
                    }
                    m_bkokisplaying = false;
                    closekoktimer();
                    closehotregiontimer();
                    onlyclosemediaplayer();
                    if(null != m_alkokfiletimeregions) {
                        if(!m_closekokimmediately.get()) {
                            try {
                                // stay KOK_AUDIOFILEINTERVALTIME temporarily before the kok-color disappears
                                Thread.sleep(KOK_ENDLASTTIME);
                            } catch (InterruptedException e) {
                            }
                        }
                        koktextcolordisappear(false);
                        if(!m_closekokimmediately.get()) {
                            kokfilesoundregion kfr = m_alkokfiletimeregions.getNext();
                            if(null == kfr) {
                                closehotregiontimer();
                                if(null != m_mutualactioncallback){
                                    if (DefaultSettings.BOOKREADTYPE_READTOME == m_ireadtype) {
                                        if (mBeingTouched) {
                                            mKokCompleted  = true;
                                            m_mutualactioncallback.playkokcompleted(false);
                                        } else {
                                            backToInitStatus();
                                            m_mutualactioncallback.playkokcompleted(true);
                                        }

                                    } else {
                                        m_mutualactioncallback.playkokcompleted(true);
                                    }
                                }
                            }
                            else{
                                if(!m_closekokimmediately.get()){
                                    try {
                                        // stay KOK_AUDIOFILEINTERVALTIME temporarily before to start next audio file
                                        Thread.sleep(KOK_AUDIOFILEINTERVALTIME);
                                    } catch (InterruptedException e) {
                                    }
                                }
                                if(!m_closekokimmediately.get() && null == m_mpkokplayer){
                                    try{
                                        int[] bound = m_alkokfiletimeregions.getBound();
                                        boolean bdone = onlystartmediaplayer(kfr, iplaypagepos, bound != null && bound.length > 0);
                                        if(!bdone) {
                                            closeplaykokprocess();
                                            if(null != m_mutualactioncallback){
                                                m_mutualactioncallback.playkokcompleted(true);
                                            }
                                        }
                                        else{
                                            if(m_mpkokplayer.gettag() != m_iinnerpage && m_iinnerpage >= 0) {
                                                closeplaykokprocess();
                                            }
                                        }
                                    }catch(Exception e){
                                        TLog.log("NewBookPageView : createnewmediaplayer : " + e);
                                    }
                                }
                            }
                        }
                    }
                    else{  // if(null != m_alkokfiletimeregions)
                        koktextcolordisappear(false);
                    }
                }
            });

            m_mpkokplayer.setOnErrorListener(new MediaPlayer.OnErrorListener(){
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    closeplaykokprocess();
                    TLog.log("NewBookPageView : createnewmediaplayer : OnErrorListener : " + what + " and " + extra);
                    return false;
                }
            });
        }catch(Exception e){
        }

        return (null != m_mpkokplayer);
    }

    private void startkoktextcolorchange(final AudiofileTimeelapsedUnit[] timeregions, final int ibegintime, final int iendtime, boolean hotregion) {
        closekoktimer();
        m_lastkokunitposforonefile = 0;
        Rect oldlastdraw = m_rckoklastdraw;
       // MyLog.d("HotRegion startkoktextcolorchange " + m_rckoklastdraw);
        m_rckoklastdraw = calculatekokrectattimepoint(timeregions[m_lastkokunitposforonefile].m_iaudiocliptimebegin, timeregions[m_lastkokunitposforonefile]);
        if (oldlastdraw != null || hotregion) {
           // MyLog.d("HotRegion startkoktextcolorchange here");
            koktextchangeColor(m_rckoklastdraw, true, false);
        }
        m_ikokfilestartrectleft = m_rckoklastdraw.left;
        m_tmkok = new Timer();
        /**
         * 以 50 毫秒 为步长 进行音频播放 与走红
         */
        m_ttkoktask = new TimerTask()  {
            @Override
            public void run()  {
                if(!updatekoktextcolorchange(timeregions, ibegintime, iendtime)) {
                    closeplaykokprocess();
                }
            }
        };
        m_tmkok.schedule(m_ttkoktask, 0, KOK_SLICETIME);
    }

    private boolean updatekoktextcolorchange(AudiofileTimeelapsedUnit[] timeregions, final int ibegintime, final int iendtime) {

        if(null == m_mpkokplayer || null == timeregions){
            return false;
        }
       // MyLog.d("KOK updatekoktextcolorchange " + ibegintime + " - " + iendtime + " rect = ");
        int ilimitlen = timeregions.length;
        if(!m_mpkokplayer.isPlaying() && !m_bkokisplaying){
            return false;
        }
        if(m_lastkokunitposforonefile >= ilimitlen){
            m_lastkokunitposforonefile = -1;
           // MyLog.de("BookPageView : updatekoktextcolorchange " + m_lastkokunitposforonefile + " >= " + ilimitlen);
            return false;
        }
        else if(m_lastkokunitposforonefile < 0) {
            m_lastkokunitposforonefile = -1;
            return false;
        }

        int iplayingtime = 0;
        try{
            iplayingtime = m_mpkokplayer.getCurrentPosition();

            if (mSpeed == DefaultSettings.SPEED_SLOW) {
                iplayingtime = (int)(iplayingtime / 1.33f);
            } else if (mSpeed == DefaultSettings.SPEED_FAST) {
                iplayingtime = (int)(iplayingtime * 1.50f);
            }
        }catch(Exception e){
            iplayingtime = iendtime;
            //MyLog.de("BookPageView : updatekoktextcolorchange : e : " + e);
        }

        try{
            boolean bistail = (m_lastkokunitposforonefile >= ilimitlen - 1);
            AudiofileTimeelapsedUnit lasttimerange = timeregions[m_lastkokunitposforonefile];
            if(null == lasttimerange){
                if (m_alrckok != null && m_alrckok.size() > 0) {
                }
                return false;
            }
            if(bistail && iplayingtime >= timeregions[m_lastkokunitposforonefile].m_iaudiocliptimeend) {
                m_rckoklastdraw = getkokatarecttail(iplayingtime, timeregions[m_lastkokunitposforonefile]);
                koktextchangeColor(m_rckoklastdraw, false, true);
            } else if (iplayingtime < lasttimerange.m_iaudiocliptimebegin) {
                if (m_alrckok != null && m_alrckok.size() > 0) {
                }
                return true;
            }
            else if(iplayingtime <= lasttimerange.m_iaudiocliptimeend) {
                m_rckoklastdraw = calculatekokrectattimepoint(iplayingtime, lasttimerange);
                koktextchangeColor(m_rckoklastdraw, false, true);
            }
            else {

                int ispan = 1;
                AudiofileTimeelapsedUnit next = null;
                next = timeregions[m_lastkokunitposforonefile + ispan];
                if(null == next) {
                    if (m_alrckok != null && m_alrckok.size() > 0) {
                    }
                    return false;
                }
                while(iplayingtime >= next.m_iaudiocliptimeend && m_lastkokunitposforonefile + ispan < ilimitlen - 1) {
                    ispan++;
                    next = timeregions[m_lastkokunitposforonefile + ispan];
                    if(null == next) {
                        if (m_alrckok != null && m_alrckok.size() > 0) {
                        }
                        return false;
                    }
                }

                Rect[] rcs = calculatekokrectsbytimepoint(timeregions, iplayingtime, ispan);
                if(1 != rcs.length && 2 != rcs.length) {
                    if (m_alrckok != null && m_alrckok.size() > 0) {
                    }
                    return false;
                }

                m_lastkokunitposforonefile += ispan;
                koktextchangeColor(rcs[0], false, true);
                if(2 == rcs.length){
                    koktextchangeColor(rcs[1], true, true);
                    m_rckoklastdraw = rcs[1];
                }
                else{
                    m_rckoklastdraw = rcs[0];
                }

                if (m_alrckok != null && m_alrckok.size() > 0) {
                }
            }
            return true;
        }catch(Exception e){
        }
        return false;
    }

    private Rect[] calculatekokrectsbytimepoint(AudiofileTimeelapsedUnit[] timeregions, int iplayingtime, int ispan) {
        ArrayList<Rect> allinercs = new ArrayList<Rect>();
        Rect rcadd = new Rect(m_rckoklastdraw);
/*    	rcadd.left -= m_iviewXoffset;
    	rcadd.right -= m_iviewXoffset;
    	rcadd.top -= m_iviewYoffset;
    	rcadd.bottom -= m_iviewYoffset;*/
        allinercs.add(rcadd);

        boolean   specialcase  = false;   //added by wang qian 懒惰猫生词表。ispan = 1
        for(int i = 1; i <= ispan; i++) {
            AudiofileTimeelapsedUnit next = timeregions[m_lastkokunitposforonefile + i];
            int iright = next.m_rc.right;
            if(iplayingtime >= next.m_iaudiocliptimebegin && iplayingtime <= next.m_iaudiocliptimeend){
                iright = next.m_rc.left + (int)(((float)(iplayingtime - next.m_iaudiocliptimebegin) / (float)(next.m_iaudiocliptimeend - next.m_iaudiocliptimebegin) * (next.m_rc.right - next.m_rc.left) + 0.499f));
            }
            else if (iplayingtime < next.m_iaudiocliptimebegin) {  //wang qian added for 懒惰猫 生字表
                specialcase = true;
            }

            if(rcadd.top == next.m_rc.top && rcadd.bottom == next.m_rc.bottom && !next.m_rc.newBlockStart){
                if (specialcase) {
                    AudiofileTimeelapsedUnit prev = timeregions[m_lastkokunitposforonefile + i - 1];
                    rcadd.right = prev.m_rc.right;
                    break;
                } else {
                    rcadd.right = iright;
                }
            }
            else{
                AudiofileTimeelapsedUnit prev = timeregions[m_lastkokunitposforonefile + i - 1];
                rcadd.right = prev.m_rc.right;

                if (specialcase) {
                    rcadd = new Rect(next.m_rc.left, next.m_rc.top, next.m_rc.left, next.m_rc.bottom);
                    allinercs.add(rcadd);
                    break;
                } else {
                    rcadd = new Rect(next.m_rc.left, next.m_rc.top, iright, next.m_rc.bottom);
                    allinercs.add(rcadd);
                }

            }
        }
        int isize = allinercs.size();
        if(isize <= 0) {
            return null;
        }
        Rect[] rcs = new Rect[isize];
        for(int i = 0; i < isize; i++) {
            rcs[i] = allinercs.get(i);
            //offsetkokrectattimepoint(rcs[i]);
        }
        allinercs.clear();
        allinercs = null;
        return rcs;
    }

    private Rect calculatekokrectattimepoint(int iplayingtime, AudiofileTimeelapsedUnit timerange){
        if(null == timerange.m_rc){
            //MyLog.d("NewBookPageView : calculatekokrectattimepoint : null error!");
            return null;
        }
        Rect rc = new Rect(timerange.m_rc.left, timerange.m_rc.top, timerange.m_rc.right, timerange.m_rc.bottom);
        //offsetkokrectattimepoint(rc);
        if(iplayingtime < timerange.m_iaudiocliptimebegin || iplayingtime > timerange.m_iaudiocliptimeend + KOK_ENDLASTTIME) {
            //MyLog.de("BookPageView : calculatekokrectattimepoint : " + iplayingtime + " excludes (" + timerange.m_iaudiocliptimebegin + ", " + (timerange.m_iaudiocliptimeend + KOK_ENDLASTTIME) + ")");
        }
        else if(iplayingtime > timerange.m_iaudiocliptimeend && iplayingtime < timerange.m_iaudiocliptimeend + KOK_ENDLASTTIME){
            rc.right = timerange.m_rc.right;
        }
        else if (iplayingtime < timerange.m_iaudiocliptimebegin) { //wang qian add for  懒惰猫生词表
            rc.right = rc.left;
        } else {
            rc.right = rc.left +
                    (int)(((float)(iplayingtime - timerange.m_iaudiocliptimebegin) / (float)(timerange.m_iaudiocliptimeend - timerange.m_iaudiocliptimebegin) * (rc.right - rc.left) + 0.499f));
        }
        return rc;
    }

    private Rect getkokatarecttail(int iplayingtime, AudiofileTimeelapsedUnit timerange){
        if(null == timerange.m_rc){
            TLog.log("BookPageView : calculatekokrectattimepoint : null error!");
            return null;
        }
        Rect rc = new Rect(timerange.m_rc.left, timerange.m_rc.top, timerange.m_rc.right, timerange.m_rc.bottom);
        //offsetkokrectattimepoint(rc);
        if(null != m_rckoklastdraw && (m_rckoklastdraw.top == rc.top && m_rckoklastdraw.bottom == rc.bottom)) {
            rc.left = m_rckoklastdraw.right;
        }
        return rc;
    }

    private void koktextchangeColor(Rect rcdraw, boolean bnewline, boolean draw) {
        if(null == rcdraw) {
            return;
        }
        Rect newrc = null;
        if(bnewline){
            m_alrckok.add(rcdraw);
        }
        else{
            synchronized(this){
                int isize = m_alrckok.size();
                if(isize <= 0) {
                    m_alrckok.add(rcdraw);
                    rcdraw.left = m_ikokfilestartrectleft;
                }
                else{
                    Rect rc = m_alrckok.get(isize - 1);
                    if(rcdraw.right < rc.right){
                        rc.right = rc.right;
                    }
                    else{
                        rc.right = rcdraw.right;
                    }
                }
            }
        }

/*		int len = m_alrckok.size();
	    if (len > 0 ) {
	    	newrc = m_alrckok.get(len - 1);
	    }
        if (newrc != null) {
        	Rect dst = maptoforegroundRegion(newrc);
	    	postInvalidate(newrc.left, newrc.top, newrc.right, newrc.bottomdst.left, dst.top, dst.right, dst.bottom);
	    } else {
	    	postInvalidate();
	    }*/
        postInvalidate();
    }

    private void offsetkokrectattimepoint(Rect rc){
        if(null != rc) {
            rc.left += m_iviewXoffset;
            rc.right += m_iviewXoffset;
            rc.top += m_iviewYoffset;
            rc.bottom += m_iviewYoffset;
        }
    }

    public void closeplaykokprocess() {
        //MyLog.d("logautokok closeplaykokprocess");
        try{
            synchronized(this){
                closekoktimer();
            }
            synchronized(this){
                closehotregiontimer();
            }
            onlyclosemediaplayer();
            synchronized(this){
                m_bkokisplaying = false;
            }
            koktextcolordisappear(m_closekokimmediately.get());
        }catch(Exception e){
        }
    }

    private void closekoktimer() {
        try{
            if(null != m_tmkok) {
                m_tmkok.cancel();
                m_tmkok = null;
            }
            if(null != m_ttkoktask) {
                m_ttkoktask.cancel();
                m_ttkoktask = null;
            }
        }catch(Exception e){
        }
        m_lastkokunitposforonefile = -1;
        //m_rckoklastdraw = null;
        m_ikokfilestartrectleft = 0;
    }

    private void onlyclosemediaplayer() {
/*
if(null != m_mpkokplayer){
	MyLog.dee("MyLog ------- BookPageView : onlyclosemediaplayer : m_mpkokplayer.m_itag = " + m_mpkokplayer.m_itag);
}
else{
	MyLog.dee("MyLog ------- BookPageView : onlyclosemediaplayer : m_mpkokplayer = " + null);
}
*/
        try{
            synchronized(this){
                if(null != m_mpkokplayer) {
                    m_mpkokplayer.stop();
                    m_mpkokplayer.release();
                    m_mpkokplayer.removetag();
                    m_mpkokplayer = null;
                    m_bkokisplaying = false;
                }
            }
        }catch(Exception e){
        }
    }

    private void koktextcolordisappear(boolean brelease) {
/*        synchronized(this){
		    m_alrckok.clear();
		}*/
        if (brelease) {
/*			synchronized(this){
			    m_alrckok.clear();
			}*/

            synchronized(this){
                m_lastkokunitposforonefile = -1;
                if(null != m_alkokfiletimeregions){
                    m_alkokfiletimeregions.clear();
                }
            }
            synchronized(this) {
                bitmapkokfore_recycle();
            }
        }
        this.postInvalidate();
    }

    /* =================================== */

    private class ArrayListtoNext<T> {

        private ArrayList<T> m_values = new ArrayList<T>();
        private int m_iindex = -1;
        private int[] mbound = null;

        public ArrayListtoNext() {
        }

        public void add(T obj) {
            m_values.add(obj);
        }

        public int size() {
            return m_values.size();
        }

        public void clear() {
            m_values.clear();
            m_iindex = -1;
            mbound = null;
        }

        public T getNext() {
            if (mbound != null && mbound.length > 0) {
                if (m_iindex < 0 || m_iindex >= mbound.length) {
                    return null;
                }
                return m_values.get(mbound[m_iindex++]);
            } else {
                if (m_iindex < 0 || m_iindex >= m_values.size()) {
                    return null;
                }
                return m_values.get(m_iindex++);
            }
        }

        public T getHead() {
            if (mbound != null && mbound.length > 0) {
                m_iindex = 0;
                return m_values.get(mbound[m_iindex++]);
            } else {
                if (m_values.size() > 0) {
                    m_iindex = 0;
                    return m_values.get(m_iindex++);
                }
            }
            return null;
        }

        public void setBound(int[] bound) {
            mbound = null;
            if (bound != null && bound.length > 0) {
                for(int i = 0; i < bound.length; i++) {
                    if (bound[i] < 0 || bound[i] >= m_values.size()) {
                        return;
                    }
                }
            }
            mbound = bound;
        }

        public T get(int index) {
            if (index < 0 || index >= m_values.size()) {
                return null;
            }
            return m_values.get(index);
        }

        public int[] getBound() {
            return mbound;
        }

    }

    private class kokfilesoundregion {
        String m_saudiofilepath = null;
        IntDouble m_iduaudiofiletimerange = null;
        AudiofileTimeelapsedUnit[] m_timeregions = null;
        int blocknumber = 0;

        public kokfilesoundregion(String saudiofilepath, IntDouble iduaudiofiletimerange, AudiofileTimeelapsedUnit[] timeregions){
            m_saudiofilepath = saudiofilepath;
            m_iduaudiofiletimerange = iduaudiofiletimerange;
            m_timeregions = timeregions;
            if (m_timeregions != null && m_timeregions.length > 0) {
                for (AudiofileTimeelapsedUnit unit : m_timeregions) {
                    if (unit.m_rc.newBlockStart) {
                        blocknumber++;
                    }
                }
            }
        }
    }

    /* ============================ */

    private class myMediaPlayer extends MediaPlayer {
        private int m_itag = -1;
        public void settag(int itag) {
            m_itag = itag;
        }
        public int gettag() {
            return m_itag;
        }
        public void removetag(){
            m_itag = -1;
        }
    }

    private void writeBmpToFile(Bitmap bmp, String filepath, boolean scale) {
        if (false) return;
        String path = System.getenv("EXTERNAL_STORAGE");
        path += File.separator + "readerpic";
        File folder = new File(path);
        if (folder != null) {
            if (!folder.exists()) {
                folder.mkdir();
            }
        }
        String filename = String.valueOf(m_iinnerpage);
        filename += filepath.substring(filepath.lastIndexOf("/") + 1, filepath.length());
        filename = filename.substring(0, filename.lastIndexOf('.'));
        if (scale) {
            filename += "_s";
        }
        filename += ".png";

        File file = new File(path + File.separator + filename);

        FileOutputStream out;
        try{
            if (file != null) {
                if (!file.exists()) {
                    file.createNewFile();
                } else {
                    file.delete();
                }
            }

            out = new FileOutputStream(file);
            CompressFormat format = Bitmap.CompressFormat.PNG;

            if(bmp.compress(format, 100, out))
            {
                out.flush();
                out.close();
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 计算两个手指之间的距离。
     *
     * @param event
     * @return 两个手指之间的距离
     */
    private double distanceBetweenFingers(MotionEvent event) {
        float disX = Math.abs(event.getX(0) - event.getX(1));
        float disY = Math.abs(event.getY(0) - event.getY(1));
        return Math.sqrt(disX * disX + disY * disY);
    }

    /**
     * 计算两次点击之间的距离。
     *
     * @param
     * @return 两个手指之间的距离
     */
    private double distanceBetweenDownEvent(float curX, float curY, float lastX, float lastY) {
        float disX = Math.abs(curX - lastX);
        float disY = Math.abs(curY - lastY);

        return Math.sqrt(disX * disX + disY * disY);
    }

    /**
     * 计算两个手指之间中心点的坐标。
     *
     * @param event
     */
    private void centerPointBetweenFingers(MotionEvent event) {
        float xPoint0 = event.getX(0);
        float yPoint0 = event.getY(0);
        float xPoint1 = event.getX(1);
        float yPoint1 = event.getY(1);
        centerPointX = (xPoint0 + xPoint1) / 2;
        centerPointY = (yPoint0 + yPoint1) / 2;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            // 分别获取到ZoomImageView的宽度和高度

            canvasWidth = getWidth();
            canvasHeight = getHeight();
        }
    }

    /**
     * 对图片进行平移处理
     *
     * @param
     */
    private void move() {

        // 根据手指移动的距离计算出总偏移值
        float translateX = m_iviewXoffset + movedDistanceX;
        float translateY = m_iviewYoffset + movedDistanceY;
        // 先按照已有的缩放比例对图片进行缩放

        m_iviewXoffset = (int)translateX;
        m_iviewYoffset = (int)translateY;
    }

    /**
     * 对图片进行缩放处理。
     *
     * @param
     */
    private void zoom() {

		float scaledWidth = m_bmpBkg.getWidth() * m_bgRatio *  m_fratio;
		float scaledHeight = m_bmpBkg.getHeight() * m_bgRatio * m_fratio;
		float translateX = 0f;
		float translateY = 0f;
		
		currentBitmapWidth = scaledWidth;
		currentBitmapHeight = scaledHeight;
		
		// 如果当前图片宽度小于屏幕宽度，则按屏幕中心的横坐标进行水平缩放。否则按两指的中心点的横坐标进行水平缩放
		if (currentBitmapWidth < canvasWidth) {
			translateX = (canvasWidth - scaledWidth) / 2f;

/*            m_iviewXoffset = (int)translateX;
            m_iviewYoffset = (int)((canvasHeight - scaledHeight) / 2f);

            return;*/

		} else {
			translateX = m_iviewXoffset * scaledRatio + centerPointX * (1 - scaledRatio);
			// 进行边界检查，保证图片缩放后在水平方向上不会偏移出屏幕
			if (translateX > 0) {
				translateX = 0;
			} else if (canvasWidth - translateX > scaledWidth) {
				translateX = canvasWidth - scaledWidth;
			}
		}
		// 如果当前图片高度小于屏幕高度，则按屏幕中心的纵坐标进行垂直缩放。否则按两指的中心点的纵坐标进行垂直缩放
		if (currentBitmapHeight < canvasHeight) {
			translateY = (canvasHeight - scaledHeight) / 2f;

/*            m_iviewXoffset = (int)((canvasWidth - scaledWidth) / 2f);
            m_iviewYoffset = (int)translateY;

            return;*/


		} else {
			translateY = m_iviewYoffset * scaledRatio + centerPointY * (1 - scaledRatio);
			// 进行边界检查，保证图片缩放后在垂直方向上不会偏移出屏幕
			if (translateY > 0) {
				translateY = 0;
			} else if (canvasHeight - translateY > scaledHeight) {
                translateY = canvasHeight - scaledHeight;
            }
		}
		// 缩放后对图片进行偏移，以保证缩放后中心点位置不变

        m_iviewXoffset = (int)translateX;
        m_iviewYoffset = (int)translateY;



    }

    public boolean   canFlip() {
        if ((mCurrentStatus == STATUS_INIT || mCurrentStatus == STATUS_IDLE) && m_fratio <= m_fratio_init) {
            return true;
        }
        return false;
    }

    public void setKokCompleted(boolean completed) {
        mKokCompleted = completed;
    }

    public void  backToInitStatus() {

        if (m_fratio <= m_fratio_init) return;
        m_fratio = m_fratio_init;
        m_iviewXoffset = m_iviewXoffset_init;
        m_iviewYoffset = m_iviewYoffset_init;
        mCurrentStatus = STATUS_INIT;
        postInvalidate();
    }

    private boolean createMediaPlayerForTitle(int itag) {
        onlyclosemediaplayer();
        m_mpkokplayer = new myMediaPlayer();
        m_mpkokplayer.settag(itag);

        m_mpkokplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
            @Override
            public void onPrepared(MediaPlayer mp) {
                if(m_mpkokplayer.gettag() != m_iinnerpage && m_iinnerpage >= 0) {
                    if(null != m_mpkokplayer) {
                        onlyclosemediaplayer();
                    }
                    return;
                }
            }
        });

        m_mpkokplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if(!m_bkokisplaying) {
                    return;
                }
                int iplaypagepos = m_mpkokplayer.gettag();
                if(m_mpkokplayer.gettag() != m_iinnerpage && m_iinnerpage >= 0) {
                    if(null != m_mpkokplayer) {
                        onlyclosemediaplayer();
                    }
                    return;
                }
                m_bkokisplaying = false;
                onlyclosemediaplayer();
                if(!m_closekokimmediately.get()) {
                    try {
                        // stay KOK_AUDIOFILEINTERVALTIME temporarily before the kok-color disappears
                        Thread.sleep(KOK_ENDLASTTIME);
                    } catch (InterruptedException e) {
                    }
                }

                if(null != m_mutualactioncallback){
                    if (DefaultSettings.BOOKREADTYPE_READTOME == m_ireadtype) {
                        if (mBeingTouched) {
                            mKokCompleted  = true;
                            m_mutualactioncallback.playkokcompleted(false);
                        } else {
                            backToInitStatus();
                            m_mutualactioncallback.playkokcompleted(true);
                        }

                    } else {
                        m_mutualactioncallback.playkokcompleted(true);
                    }
                }
            }
        });

        m_mpkokplayer.setOnErrorListener(new MediaPlayer.OnErrorListener(){
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                onlyclosemediaplayer();
                m_bkokisplaying = false;
                TLog.log("NewBookPageView : createMediaPlayerForTitle : OnErrorListener : " + what + " and " + extra);
                return false;
            }
        });

        return (null != m_mpkokplayer);
    }

    public void setReadType(int type) {
        m_ireadtype = type;
    }

    public void setSpeed(int speed) {

        mSpeed = speed;

    }

 /*   public void setParentLayout(NewContainerView layout) {
        mParentLayout = layout;
    }*/

    public int getHotRegionIndex(Point pt, float fratio) {
        if(null == pt) {
            return -1;
        }
        if (m_pd == null) {
            return -1;
        }

        ArrayList<HotRegionData> hotregionlist = m_pd.getHotRegionData();
        if (hotregionlist != null && hotregionlist.size() > 0) {
            for (int i = 0; i < hotregionlist.size() ;i++) {
                HotRegionData data  = hotregionlist.get(i);
                Rect hotRegion = new Rect();
/*                hotRegion.left = (int)((data.mCenterX - mHotRegionStopBmp.getWidth() / 2)* fratio + 0.499f);
                hotRegion.top = (int)((data.mCenterY - mHotRegionStopBmp.getHeight() / 2)* fratio + 0.499f);
                hotRegion.right = hotRegion.left + (int)(mHotRegionStopBmp.getWidth() * fratio);
                hotRegion.bottom = hotRegion.top + (int)(mHotRegionStopBmp.getHeight() * fratio);*/

                hotRegion.left = (int)((data.mCenterX) * m_fratio) - (int)(mSpeakerWidth * (m_fratio /(m_fratio_init * 2)));
                hotRegion.top = (int)((data.mCenterY) * m_fratio) - (int)(mSpeakerHeight * (m_fratio /(m_fratio_init * 2)));
                hotRegion.right = hotRegion.left  + (int)(mSpeakerWidth * (m_fratio /m_fratio_init));
                hotRegion.bottom = hotRegion.top + (int)(mSpeakerHeight * (m_fratio /m_fratio_init));

                if (pt.x >= hotRegion.left && pt.x <= hotRegion.right && pt.y >= hotRegion.top && pt.y <= hotRegion.bottom ) {
                    return i;
                }

            }
        }
        return -1;
    }


    boolean  mHotRegionPlay1 = false;
    private void starthotregiontimer() {

        closehotregiontimer();
        mHotRegionPlay1 = false;
        m_tmHotRegion = new Timer();
        m_ttHotRegionTask = new TimerTask() {

            @Override
            public void run() {

                if (mHotRegionPlay1) {
                    mHotRegionPlay1 = false;
                } else {
                    mHotRegionPlay1 = true;
                }

                m_playHotRegionHandler.sendEmptyMessage(1);
            }
        };
        m_tmHotRegion.schedule(m_ttHotRegionTask, 0, 500);
    }

    private void closehotregiontimer() {

        try {
            if (null != m_tmHotRegion) {
                m_tmHotRegion.cancel();
                m_tmHotRegion = null;
            }
            if (null != m_ttHotRegionTask) {
                m_ttHotRegionTask.cancel();
                m_ttHotRegionTask = null;
            }
        } catch (Exception e) {
        }
    }



}
